/**
 * 预警设置
 */
angular.module('inspinia',['uiSwitch','infinity.angular-chosen']).controller("jumpRouteBeforeSettingCtrl", function($scope, $http, $state, $stateParams, i18nService,SweetAlert,$document) {
	$scope.paginationOptions=angular.copy($scope.paginationOptions);
	i18nService.setCurrentLang('zh-cn');

	$scope.msgReceiver = [{msg:"",type:0},{msg:"",type:0},{msg:"",type:0},{msg:"",type:0},{msg:"",type:0}];
	$scope.beforeGroup = [];

	$scope.query = function() {
		$http.post('jumpRoute/beforeWarningTemplate',"",
       		 {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
        ).success(function(result){
        	if(result.status){
        		var templates = result.data.templates;
				angular.forEach(templates, function(item){
					$scope.msgReceiver[item.warnType - 1].msg = item.msgReceiver;
					$scope.msgReceiver[item.warnType - 1].type = item.warnType;
				});

				var jumpWarns = result.data.jumpWarns;
				if(jumpWarns.length == 0){
					$scope.beforeGroup = [{}];
				}else{
					angular.forEach(jumpWarns, function(item){
						var before = {
							"id": item.id,
							"jumpId": item.jumpId,
							"warnTime": item.warnTimeStr,
							"scale": item.scale
						}
						$scope.beforeGroup.push(before);
					});
				}
			}
        }).error(function(){
        }); 
	};
	$scope.query();

	$scope.update=function(){
		for(i=0;i<$scope.beforeGroup.length;i++){
			if(!$scope.beforeGroup[i].warnTime){
				$scope.notice("预警时间不能为空");
				return ;
			}
			if(!$scope.beforeGroup[i].jumpId){
				$scope.notice("预警路由ID不能为空");
				return ;
			}
			if(!$scope.beforeGroup[i].scale){
				$scope.notice("预警比例不能为空");
				return ;
			}
			if($scope.beforeGroup[i].scale <= 0){
				$scope.notice("预警比例不能为0");
				return ;
			}
		}
		var data = {
			msgReceiver: $scope.msgReceiver,
			beforeGroup: $scope.beforeGroup
		}
		$http.post("jumpRoute/updateBeforeWarningTemplate",angular.toJson(data)).success(function(data){
			if(data.status){
				$scope.notice(data.msg);
				$state.transitionTo('org.routeMonitor',null,{reload:true});
			} else {
				$scope.notice(data.msg);
			}
		});
	}

	$scope.addBeforeGroup = function(){
		$scope.beforeGroup.push({});
	}

	$scope.deleteBeforeGroup = function(index){
		$scope.beforeGroup.splice(index, 1);
	}

	$scope.toLimit = function(item,fieldName,oldValue){
		if(item[fieldName]){
			if(/^\d*(\.\d{0,2})?$/.test(item[fieldName])==false){
				item[fieldName] = oldValue;
			}
		}
	};

});